package model

import (
	"context"
	"fmt"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ LeaderboardsBucketsModel = (*customLeaderboardsBucketsModel)(nil)

type (
	// LeaderboardsBucketsModel is an interface to be customized, add more methods here,
	// and implement the added methods in customLeaderboardsBucketsModel.
	LeaderboardsBucketsModel interface {
		leaderboardsBucketsModel
		RowBuilder() squirrel.SelectBuilder
		Truncate(ctx context.Context)
	}

	customLeaderboardsBucketsModel struct {
		*defaultLeaderboardsBucketsModel
	}
)

// NewLeaderboardsBucketsModel returns a model for the database table.
func NewLeaderboardsBucketsModel(conn sqlx.SqlConn, c cache.CacheConf) LeaderboardsBucketsModel {
	return &customLeaderboardsBucketsModel{
		defaultLeaderboardsBucketsModel: newLeaderboardsBucketsModel(conn, c),
	}
}

func (m *defaultLeaderboardsBucketsModel) RowBuilder() squirrel.SelectBuilder {
	return squirrel.Select(leaderboardsBucketsRows).From(m.table)
}

func (m defaultLeaderboardsBucketsModel) Truncate(ctx context.Context) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err == nil {
		var resp []*LeaderboardsBuckets
		err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
		if err == nil {
			for _, r := range resp {
				m.Delete(ctx, r.Id)
			}
			m.ExecNoCacheCtx(ctx, fmt.Sprintf("TRUNCATE %s", m.tableName()))
		}
	}
}
